package com.观察者模式;

import java.util.ArrayList;

/**
 * 抽象股民：抽象观察者
 * @author Fang Ruichuan
 * @date 2022-09-09 13:57
 */
public interface Investor {
    void response(Stock stock);
}

// 股民：具体观察者
class ConcreteInvestor implements Investor {

    private String name;

    public ConcreteInvestor(String name) {
        this.name = name;
    }

    @Override
    public void response(Stock stock) {
        System.out.println("提示股民: " + name);
        System.out.println("------股票: " + stock.getStockName());
        System.out.println("------价格波动幅度超过5%");
        System.out.println("新价格是: " + stock.getPrice());
    }
}

// 股票：观察目标
class Stock {
    private ArrayList<Investor> investors;
    private String stockName;
    private double price;

    public Stock(String stockName, double price) {
        this.stockName = stockName;
        this.price = price;
        this.investors = new ArrayList<>();
    }

    public void attach(Investor investor) {
        investors.add(investor);
    }

    public void detach(Investor investor) {
        investors.remove(investor);
    }

    public void notifyInvestor() {
        investors.forEach(in -> {
            in.response(this);
        });
    }

    public String getStockName() {
        return stockName;
    }

    public void setStockName() {
        this.stockName = stockName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        double range = Math.abs(price - this.price) / this.price;
        this.price = price;
        if (range >= 0.05) {
            this.notifyInvestor();
        }
    }
}

